import React from 'react'
import { useHistory } from 'react-router-dom'
import { Form, Input, Button, message } from 'antd'
import { useDispatch } from 'react-redux'
import { userRegister } from '@/api/user'
import { setMyInfo } from '@/stores/user'
import { registerParams } from '@/types/user'
import './index.scss'

const Register = () => {
  const dispatch = useDispatch()
  const history = useHistory()

  const onclickRegister = async(data: registerParams) => {
    try {
      const res = await userRegister(data)

      localStorage.setItem('token', res.data.token)
      dispatch(setMyInfo(res.data))
      history.push('/')
      message.success('注册成功')
    } catch (err) {
      console.log(err)
    }
  }

  return (
    <div className="register">
      <Form
        autoComplete="off"
        labelAlign="left"
        labelCol={{ span: 6 }}
        onFinish={onclickRegister}
      >
        <Form.Item
          label="邮箱"
          name="email"
          rules={[{ required: true, message: '请输入你的邮箱地址' }]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          label="密码"
          name="password"
          rules={[{ required: true, message: '请输入密码' }]}
        >
          <Input.Password />
        </Form.Item>
        <Form.Item
          label="姓名"
          name="name"
          rules={[{ required: true, message: '请输入你的姓名' }]}
        >
          <Input />
        </Form.Item>
        <Form.Item>
          <Button
            className="register-btn"
            htmlType="submit"
            type="primary"
          >
            注册
          </Button>
        </Form.Item>
      </Form>
    </div>
  )
}

export default Register
